package doc2db.interfaces.action;

import doc2db.Keey;
import doc2db.UserProp;
import doc2db.interfaces.mainWindow.MyFrame;
import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ProgressMonitor;

/**
 *
 * @author yura
 */
public class Doc2DbDirAction extends Doc2DbAction{
    private boolean yesToAll = false;
    private String nameToAll = "";
    
    /** Recursive procesed all file in dir: if node file in dir is dir ot,
     * procesed all file in this dir ... */
    public boolean recursive = true;

    public Doc2DbDirAction(MyFrame fr, JTextField f, JTextField tn,
            JEditorPane d, JEditorPane w, String fn, boolean b) {
        super(fr, f, tn, d, w, fn, b);
    }

    public Doc2DbDirAction(MyFrame fr, JTextField f, JTextField tn,
            JEditorPane d, JEditorPane w, String fn) {
        super(fr, f, tn, d, w, fn);
    }

    public Doc2DbDirAction(MyFrame fr, JTextField f, JTextField tn,
            JEditorPane d, JEditorPane w, boolean b) {
        super(fr, f, tn, d, w, b);
    }

    public Doc2DbDirAction(MyFrame fr, JTextField f, JTextField tn,
            JEditorPane d, JEditorPane w) {
        super(fr, f, tn, d, w);
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        if (chek()) {
            errMsg("Неверное имя файла");
            return;
        }

        String textfile = file.getText();
        final String textname;// = fname.getText();
        final Set<String> names = new HashSet<String>();
        File pf = new File(textfile).getParentFile();

        if (fname.getText().trim().isEmpty()){
            textname = "Dir_" + this.toUnicodeIdentifier(pf.getName());
        } else {
            textname = fname.getText();
        }

        this.addDocFiles(pf, names);

        boolean beforetn = Keey.tableName;
        Keey.tableName = true;
        Keey.tableNameValue = textname;
        fname.setText(textname);

        yesToAll = false;
        Keey.setIsMas(true);
        int size = names.size();

        final ProgressMonitor pm = new ProgressMonitor(frame.pane,
                "Обработка каталога - '" + textname + "'", "", 0, size);

        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                procFile(names, textname, pm);
                Keey.setIsMas(false);

                pm.setNote("Вывод таблицы");
                
                if (lastTable != null) {
                    showTabl(lastTable);
                }

                pm.close();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();

        Keey.tableName = beforetn;

        file.setText(textfile);
        fname.setText(textname);
    }

    /**
     * Processing all files in the queue
     * @param names canonical file names
     * @param textname table name
     * @param pm monitor to show process
     * @throws HeadlessException when show dialogs,
     * if GraphicsEnvironment.isHeadless returns true
     */
    private void procFile(Set<String> names, String textname, ProgressMonitor pm)
            throws HeadlessException {
        int i = 1;
        int iterator = 0;
        for (String s : names) {
            if (!yesToAll) {
                if (Keey.tableName) {
                    getTabName(textname + i++, s, i);
                }
            }
            file.setText(s);
            //super.actionPerformed(e);
            try {
                //doc2db.fileWorker.ParseDocument.parse(ParseDocument.java:129)
                super.submitFile();
            } catch (ArrayIndexOutOfBoundsException ex) {
                errMsg("Чересчур много таблиц в документе:\n" + s);
            } catch (Exception ex) {
                errMsg("Произошла ошибка при обработке:\n" + ex);
            }
            pm.setNote(s);
            pm.setProgress(++iterator);
            if (pm.isCanceled()) {
                Toolkit.getDefaultToolkit().beep();
                break;
            }
        }
        //pm.close();
    }

    /**
     * recursive add all file names in pf dir, if pf is file
     * adding only this file
     * @param pf file with data
     * @param names set, where stored file names
     */
    private void addDocFiles(final File pf, Set<String> names) {
        if (pf.exists()) {
            for (File somefile : pf.listFiles()) {
                if (somefile.getName().endsWith(".doc")) {
                    names.add(somefile.getAbsolutePath());
                }
                if (somefile.isDirectory() && recursive) {
                    this.addDocFiles(somefile, names);
                }
            }
        }
    }

    /**
     * 
     * @param tn
     * @param fn
     * @param num
     * @return
     */
    private String getTabName(String tn, String fn, int num){
        JPanel pan = new JPanel(new BorderLayout());
        final JDialog dlg = new JDialog(new JFrame(), "выбор", true);

        dlg.getContentPane().add(pan, BorderLayout.CENTER);

        String str = fn;
        if (str.length() > 24) {
            String arr [] = str.split(Keey.sp);
            str = str.substring(0, 10) + " ... " + Keey.sp + arr[arr.length - 1];
        }

        JLabel l1 = new JLabel("<html><p>Имя для таблиц(и) из файла</p><p> \"" + str + "\" :");
        l1.setToolTipText(fn);
        l1.setFont(UserProp.paneFont);
        l1.setMinimumSize(l1.getPreferredSize());
        l1.setMaximumSize(l1.getMinimumSize());

        final JTextField t1 = new JTextField(tn, 34);
        t1.setFont(UserProp.textFont);
        t1.setMinimumSize(t1.getPreferredSize());
        t1.setMaximumSize(t1.getMinimumSize());
        t1.select(tn.length() - ("" + num).length(), tn.length() );

        Box b = Box.createVerticalBox();

        Box h1 = Box.createHorizontalBox();
        h1.add(Box.createHorizontalStrut(4));
        h1.add(l1);
        h1.add(Box.createGlue());

        b.add(h1);
        b.add(Box.createVerticalStrut(14));
        b.add(t1);
        b.add(Box.createVerticalStrut(14));

        pan.add(b, BorderLayout.CENTER);

        JButton no = new JButton(new AbstractAction("нет") {
            @Override
            public void actionPerformed(ActionEvent e) {
                fname.setText("");
                dlg.setVisible(false);
            }
        });

        JButton yes = new JButton(new AbstractAction("да") {
            @Override
            public void actionPerformed(ActionEvent e) {
                fname.setText(t1.getText());
                dlg.setVisible(false);
            }
        });

        JButton yesforall = new JButton(new AbstractAction("да для всех") {
            @Override
            public void actionPerformed(ActionEvent e) {
                yesToAll = true;
                nameToAll = t1.getText();
                fname.setText(t1.getText());
                dlg.setVisible(false);
            }
        });

        t1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fname.setText(t1.getText());
                dlg.setVisible(false);
            }
        });

        yesforall.setMinimumSize(yesforall.getPreferredSize());

        yes.setSize(yesforall.getPreferredSize());
        yes.setPreferredSize(yesforall.getPreferredSize());
        yes.setMinimumSize(yesforall.getPreferredSize());

        no.setSize(yesforall.getPreferredSize());
        no.setPreferredSize(yesforall.getPreferredSize());
        no.setMinimumSize(yesforall.getPreferredSize());

        Box h = Box.createHorizontalBox();
        h.add(Box.createGlue());
        h.add(no);
        h.add(Box.createHorizontalStrut(2));
        h.add(yes);
        h.add(Box.createHorizontalStrut(2));
        h.add(yesforall);
        h.add(Box.createGlue());

        pan.add(h, BorderLayout.SOUTH);

        dlg.pack();
        dlg.setLocationRelativeTo(null);
        dlg.setVisible(true);

        return t1.getText();
    }

    private String toUnicodeIdentifier(String name){
        StringBuilder sb = new StringBuilder();
        for (char o : name.toCharArray()) {
            if (Character.isUnicodeIdentifierPart(o)){
                sb.append(o);
            } else {
                sb.append('_');
            }
        }
        return sb.toString();
    }

}
